﻿using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using IOP.Extension.DependencyInjection;
using Silk.NET.Vulkan;

namespace VkSample112;

[ModulePriority(ModulePriority.RenderPass)]
public class RenderPassModule : VulkanModule, IVulkanRenderWapperModule
{
    public VulkanRenderWapper RenderWapper { get; set; }
    [Autowired]
    private ILogger<RenderPassModule> _Logger { get; set; }

    protected override Task Load(VulkanGraphicsManager graphicsManager)
    {
        try
        {
            var lDevice = graphicsManager.VulkanDevice;
            var pipeCache = lDevice.PipelineCache;
            var disapatcher = RenderWapper.GetRenderDispatcher<VulkanSwapchainRenderDispatcher>();
            var presentPass = disapatcher.SwapchainRenderPass;
            var area = RenderWapper.RenderArea;
            var fence = lDevice.CreateFence();

            var pCommand = lDevice.CreateCommandPool((device, option) =>
            {
                option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
            }).CreatePrimaryCommandBuffer();
            var mainGroup = graphicsManager.CreatePrimaryRenderGroup("Main", null)
                .Binding(pCommand, lDevice, presentPass, new Silk.NET.Vulkan.Semaphore[] { disapatcher.ImageAvailableSemaphore, disapatcher.RenderFinishSemaphore }, new Fence[] { fence.RawHandle });
            mainGroup.CreateGroupRenderingAction((builder) => builder.UseMiddleware<MainMiddleware>());
            return Task.CompletedTask;
        }
        catch (Exception e)
        {
            _Logger.LogError(e.Message + "\r\n" + e.StackTrace);
            return Task.FromException(e);
        }
    }

    protected override Task Unload(VulkanGraphicsManager manager)
    {
        return Task.CompletedTask;
    }
}
